package cn.ivicar.app.sae;

import org.apache.commons.lang.StringUtils;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.exception.NotAuthorizedException;
import cn.com.carsmart.sae.SaeUtils;
import cn.com.carsmart.sae.authc.AuthenticationInfo;
import cn.com.carsmart.sae.authc.Authenticator;
import cn.com.carsmart.sae.authc.SimpleAuthenticationInfo;
import cn.com.carsmart.sae.principal.ShiroPrincipal;
import cn.com.carsmart.sae.token.AuthenticationToken;
import cn.com.carsmart.sae.token.UsernamePasswordDomainToken;
import cn.com.carsmart.ws.model.Customer;
import cn.ivicar.app.guice.AppGuiceConfig;
import cn.ivicar.passport.service.PassportService;

public class SampleSaeAuthenticator implements Authenticator {
	
	PassportService passportService ;

    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws CarsmartException {
        if (!(token instanceof UsernamePasswordDomainToken)) {
            throw new BadRequestException("common", "Unsupported token");
        }
        
        if(passportService == null){
        	passportService = AppGuiceConfig.getStaticInjector().getInstance(PassportService.class);
        }

        // 普通认证方式
        String username = null == token.getPrincipal() ? "" : token.getPrincipal().toString();
        if (StringUtils.isBlank(username)) {
            throw new NotAuthorizedException("common", "登录名不能为空");
        }

        Customer customer = passportService.getByMobile(username);
        if (passportService.getByMobile(username) == null) {
            throw new BadRequestException("common", "用户信息不存在");
        } 

        ShiroPrincipal.UserInfo userInfo = new ShiroPrincipal.UserInfo(customer.getId().intValue(),
                customer.getNickname(), customer.getEmail(), customer.getMobile(), null);

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(null, null, null, null, userInfo);
        SaeUtils.getContext().setAttribute("ucCustomerId", customer.getId());

        return info;
    }

}
